package com.emenu;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.emenu.LoginProgress.DownloadProcess;
import com.emenu.application.StaticObject;
import com.emenu.bean.BusHitDetail;
import com.emenu.bean.BusHitMaster;
import com.emenu.bean.Localparm;
import com.emenu.bean.PubTable;
import com.emenu.bean.PubTimer;
import com.emenu.bean.SubMenu;
import com.emenu.bean.User;
import com.emenu.common.Common;
import com.emenu.common.GetWebServiceData;
import com.emenu.common.JsonUntil;
import com.emenu.common.NetUntil;
import com.emenu.common.PostWebServiceData;
import com.emenu.common.SaveMenuImg;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.ListFragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;

public class SurePost extends Activity {
	private EditText table;
	private TextView tablename;
	private EditText time_code;
	private EditText human_num;
	private EditText towel_num;
	private EditText tea_num;
	private EditText post_type;
	private EditText user_code;
	private EditText us_pw;

	private TextView manage_code_view;
	private TextView manage_PW_view;
	private EditText manage_code;
	private EditText manage_pw;

	private ImageButton jia1;
	private ImageButton jia2;
	private ImageButton jia3;
	private ImageButton jia4;
	private ImageButton jia5;
	private ImageButton jian1;
	private ImageButton jian2;
	private ImageButton jian3;
	private ImageButton jian4;
	private ImageButton jian5;
	private ImageButton tableleft;

	private CheckBox cb1;
	private CheckBox cb2;
	private CheckBox cb3;
	private CheckBox cb4;
	private CheckBox cb5;

	private Button post;
	private Button button_back;

	public StaticObject SO;
	List<PubTable> PubTablelist;
	List<PubTimer> PubTimerlist;
	private BusHitMaster busHitMaster = new BusHitMaster();;

	private int hit_posttype = 0;
	private String Hit_time_code = "1";
	private int maxtimecode = 0;
	private int mintimecode = 0;

	private String Dinner_code;
	private String table_code;
	private boolean notable = false;

	private String tempwsdl;
	private SharedPreferences settings;
	public static final String SET_NAME = "jpSetFile";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.surepost);

		findViewsById();
		setListener();

		settings = getSharedPreferences(SET_NAME, Activity.MODE_WORLD_READABLE
				| Activity.MODE_WORLD_WRITEABLE | Activity.MODE_APPEND);

		tempwsdl = settings.getString("url", "");

		manage_code_view.setVisibility(View.INVISIBLE);
		manage_PW_view.setVisibility(View.INVISIBLE);
		manage_code.setVisibility(View.INVISIBLE);
		manage_pw.setVisibility(View.INVISIBLE);

		human_num.setText(1 + "");
		towel_num.setText(1 + "");
		tea_num.setText(1 + "");

		SO = (StaticObject) getApplication();
		PubTablelist = SO.getPubTableList();
		PubTimerlist = SO.getPub_timerList();
		user_code.setText(SO.getStaticUser());

		maxtimecode = Integer.parseInt(PubTimerlist
				.get(PubTimerlist.size() - 1).getCode());

		mintimecode = Integer.parseInt(PubTimerlist.get(0).getCode());

		for (Localparm lp : SO.getParmList()) {
			if ("100000".equals(lp.getCode())) {
				Dinner_code = lp.getParmvalue();
				break;
			}
		}

		Hit_time_code = SO.getStaticTimeCode();

		for (PubTimer pt : SO.getPub_timerList()) {
			if (pt.getCode().equals(Hit_time_code)) {
				time_code.setText(pt.getName());

			}

		}

	}

	/** 视图 样式 */
	private void findViewsById() {
		table = (EditText) findViewById((R.id.table));
		tablename = (TextView) findViewById((R.id.tablename));
		time_code = (EditText) findViewById((R.id.time_code));
		human_num = (EditText) findViewById((R.id.human_num));
		towel_num = (EditText) findViewById((R.id.towel_num));
		tea_num = (EditText) findViewById((R.id.tea_num));
		post_type = (EditText) findViewById((R.id.surepost_type));
		user_code = (EditText) findViewById((R.id.user_code));
		us_pw = (EditText) findViewById((R.id.us_pw));

		manage_code_view = (TextView) findViewById((R.id.manager_code_view));
		manage_PW_view = (TextView) findViewById((R.id.manager_pw_view));
		manage_code = (EditText) findViewById((R.id.manager_code));
		manage_pw = (EditText) findViewById((R.id.manager_pw));

		cb1 = (CheckBox) findViewById(R.id.cb1);
		cb2 = (CheckBox) findViewById(R.id.cb2);
		cb3 = (CheckBox) findViewById(R.id.cb3);
		cb4 = (CheckBox) findViewById(R.id.cb4);
		cb5 = (CheckBox) findViewById(R.id.cb5);

		post = (Button) findViewById(R.id.sure_post);
		button_back = (Button) findViewById(R.id.menu_cancel);

		jia1 = (ImageButton) findViewById(R.id.jia_1);
		;
		jia2 = (ImageButton) findViewById(R.id.jia_2);
		;
		jia3 = (ImageButton) findViewById(R.id.jia_3);
		;
		jia4 = (ImageButton) findViewById(R.id.jia_4);
		;
		jia5 = (ImageButton) findViewById(R.id.jia_5);
		;

		jian1 = (ImageButton) findViewById(R.id.jian_1);
		;
		jian2 = (ImageButton) findViewById(R.id.jian_2);
		;
		jian3 = (ImageButton) findViewById(R.id.jian_3);
		;
		jian4 = (ImageButton) findViewById(R.id.jian_4);
		;
		jian5 = (ImageButton) findViewById(R.id.jian_5);
		;
		tableleft = (ImageButton) findViewById(R.id.tableleft);

	}

	/** 设置监听器 */
	private void setListener() {
		// edit监听器
		// table.addTextChangedListener(tablewatcher);
		post.setOnClickListener(postlisten);
		button_back.setOnClickListener(backlisten);

		jia1.setOnClickListener(jia1Listener);
		jia2.setOnClickListener(jia2Listener);
		jia3.setOnClickListener(jia3Listener);
		jia4.setOnClickListener(jia4Listener);
		jia5.setOnClickListener(jia5Listener);

		jian1.setOnClickListener(jian1Listener);
		jian2.setOnClickListener(jian2Listener);
		jian3.setOnClickListener(jian3Listener);
		jian4.setOnClickListener(jian4Listener);
		jian5.setOnClickListener(jian5Listener);

		tableleft.setOnClickListener(tableftListener);

	}

	/***
	 * public TextWatcher tablewatcher = new TextWatcher() {
	 * 
	 * @Override public void afterTextChanged(Editable s) { for (PubTable pt :
	 *           PubTablelist) { if
	 *           (pt.getHelpcode().equals(String.valueOf(table.getText()))) {
	 *           tablename.setText(pt.getName());
	 * 
	 *           notable = false; String num = pt.getMaxCount() + ""; table_code
	 *           = pt.getCode(); human_num.setText(num);
	 * 
	 *           towel_num.setText(num); tea_num.setText(num);
	 * 
	 *           break;
	 * 
	 *           } else { notable = true; }
	 * 
	 *           }
	 * 
	 *           }
	 * @Override public void beforeTextChanged(CharSequence s, int start, int
	 *           count, int after) { // TODO Auto-generated method stub
	 * 
	 *           }
	 * @Override public void onTextChanged(CharSequence s, int start, int
	 *           before, int count) {
	 * 
	 *           }
	 * 
	 *           };
	 ***/

	private OnClickListener postlisten = new OnClickListener() {

		@Override
		public void onClick(View v) {

			if (notable || table_code == null || table_code == "") {

				noTable();
				return;
			}
			busHitMaster.setId(-1);
			busHitMaster.setCode("-1");
			busHitMaster.setHitcode("-1");
			busHitMaster.setDinner_code(Dinner_code);
			busHitMaster.setTable_code(table_code);
			busHitMaster.setConsume_date("");
			busHitMaster.setTime_code(Hit_time_code + "");

			if (hit_posttype == 2 || hit_posttype == 3) {
				busHitMaster.setManager_code(user_code.getText() + "");
			} else {
				busHitMaster.setManager_code("");
			}
			busHitMaster.setAmount(Integer.parseInt(human_num.getText() + ""));
			busHitMaster.setHit_type(hit_posttype);
			busHitMaster.setPrintcount(0);
			busHitMaster.setPrintuser(SO.getStaticUser());
			busHitMaster.setPrintdatetime("");

			busHitMaster.setCreateuser(SO.getStaticUser());
			busHitMaster.setCreatedatetime("");
			busHitMaster.setUpdateuser(SO.getStaticUser());
			busHitMaster.setUpdatedatetime("");
			busHitMaster.setRemark("");
			busHitMaster.setUpload(0);
			busHitMaster.setC1("");
			busHitMaster.setC2("");
			busHitMaster.setC3("");
			busHitMaster.setC4("");

			// ////////

			Boolean isCheck = false;
			Boolean isManagerCheck = false;
			// 是否退菜或赠品
			Boolean ispostype = false;

			if (hit_posttype == 2 || hit_posttype == 3) {
				ispostype = true;
			}

			for (User user : SO.getUserList()) {
				if ((user_code.getText() + "").equals(user.getCode())) {
					if ((us_pw.getText() + "").equals(SO.getStaticUserPW())) {
						isCheck = true;
					}
					if (ispostype) {
						isManagerCheck = JsonUntil.isPassword(
								manage_pw.getText() + "", user.getPassword());
					}

					break;
				}

			}

			if (!isCheck) {
				Common.alertalam(SurePost.this, "服务员账户或密码出错", "账户或密码出错！重新输入！");
				return;
			} else if (ispostype && (!isManagerCheck)) {
				Common.alertalam(SurePost.this, "经理账户或密码出错", "账户或密码出错！重新输入！");
				return;
			}

			if (NetUntil.isConnect(SurePost.this)) {

				// 异步发送webservice
				new sendTask().execute((Void) null);

			} else {
				Common.alertalam(SurePost.this, "网络出错", "网络出错！请关闭后再次发送！");
			}

		 

		}
	};

	private OnClickListener backlisten = new OnClickListener() {
		@Override
		public void onClick(View v) {
			finish();
		}
	};

	private OnClickListener jia1Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Hit_time_code = (Integer.parseInt(Hit_time_code) + 1) + "";

			if (Integer.parseInt(Hit_time_code) > maxtimecode) {
				Hit_time_code = maxtimecode + "";
			}

			for (PubTimer pt : PubTimerlist) {
				if (Hit_time_code.equals(pt.getCode())) {
					time_code.setText(pt.getName());
					break;
				}
			}
		}
	};
	private OnClickListener jia2Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int i = Integer.parseInt(human_num.getText() + "");
			i++;

			human_num.setText(i + "");

		}
	};
	private OnClickListener jia3Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int i = Integer.parseInt(towel_num.getText() + "");
			i++;

			towel_num.setText(i + "");

		}
	};
	private OnClickListener jia4Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int i = Integer.parseInt(tea_num.getText() + "");
			i++;

			tea_num.setText(i + "");
		}
	};
	private OnClickListener jia5Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			hit_posttype++;

			if (hit_posttype > 3) {
				hit_posttype = 3;
			}

			if (hit_posttype == 0) {
				post_type.setText("正常");
			} else if (hit_posttype == 1) {
				post_type.setText("加菜");
			} else if (hit_posttype == 2) {
				post_type.setText("赠菜");
			} else if (hit_posttype == 3) {
				post_type.setText("退菜");
			}
			if (hit_posttype == 2 || hit_posttype == 3) {
				manage_code_view.setVisibility(View.VISIBLE);
				manage_PW_view.setVisibility(View.VISIBLE);
				manage_code.setVisibility(View.VISIBLE);
				manage_pw.setVisibility(View.VISIBLE);

			} else {
				manage_code_view.setVisibility(View.INVISIBLE);
				manage_PW_view.setVisibility(View.INVISIBLE);
				manage_code.setVisibility(View.INVISIBLE);
				manage_pw.setVisibility(View.INVISIBLE);

			}
		}
	};
	private OnClickListener jian1Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			// Hit_time_code--;
			Hit_time_code = (Integer.parseInt(Hit_time_code) - 1) + "";

			if (Integer.parseInt(Hit_time_code) < mintimecode) {
				Hit_time_code = mintimecode + "";
			}

			for (PubTimer pt : PubTimerlist) {
				if (Hit_time_code.equals(pt.getCode())) {
					time_code.setText(pt.getName());
					break;
				}
			}

		}
	};

	private OnClickListener jian2Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int i = Integer.parseInt(human_num.getText() + "");
			i--;
			if (i > 0) {
				human_num.setText(i + "");
			}

		}
	};
	private OnClickListener jian3Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int i = Integer.parseInt(towel_num.getText() + "");
			i--;
			if (i > 0) {
				towel_num.setText(i + "");
			}

		}
	};
	private OnClickListener jian4Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int i = Integer.parseInt(tea_num.getText() + "");
			i--;
			if (i > 0) {
				tea_num.setText(i + "");
			}

		}
	};
	private OnClickListener jian5Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			hit_posttype--;
			if (hit_posttype < 0) {
				hit_posttype = 0;
			}

			if (hit_posttype == 0) {
				post_type.setText("正常");
			} else if (hit_posttype == 1) {
				post_type.setText("加菜");
			} else if (hit_posttype == 2) {
				post_type.setText("赠菜");
			} else if (hit_posttype == 3) {
				post_type.setText("退菜");
			}

			if (hit_posttype == 2 || hit_posttype == 3) {
				manage_code_view.setVisibility(View.VISIBLE);
				manage_PW_view.setVisibility(View.VISIBLE);
				manage_code.setVisibility(View.VISIBLE);
				manage_pw.setVisibility(View.VISIBLE);
			} else {
				manage_code_view.setVisibility(View.INVISIBLE);
				manage_PW_view.setVisibility(View.INVISIBLE);
				manage_code.setVisibility(View.INVISIBLE);
				manage_pw.setVisibility(View.INVISIBLE);
			}

		}
	};

	private OnClickListener tableftListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			for (PubTable pt : PubTablelist) {
				if (pt.getHelpcode().equals(String.valueOf(table.getText()))) {
					tablename.setText(pt.getName());

					notable = false;
					String num = pt.getMaxCount() + "";
					table_code = pt.getCode();
					human_num.setText(num);

					towel_num.setText(num);
					tea_num.setText(num);

					break;

				} else {
					notable = true;
				}

			}

		}
	};

	// 叫单
	private void CalledSingle(int type) {
		for (BusHitDetail bhd : SO.getBusHitDetailList()) {
			if (bhd.getRljtype() == type) {
				bhd.setCalledSingle(1);
			}

		}
	}

	// 发送
	private void send(int type) {
		for (BusHitDetail bhd : SO.getBusHitDetailList()) {
			if (bhd.getRljtype() == type) {
				bhd.setUpload(1);
			}

		}
	}

	public static boolean isDateBefore(String date2) {
		try {
			Date date1 = new Date();
			DateFormat df = DateFormat.getDateTimeInstance();
			System.out.println(date1.before(df.parse(date2)));
			return date1.before(df.parse(date2));
		} catch (ParseException e) {
			System.out.print(e.getMessage());
			return false;
		}

	}

	public static boolean isDateAfter(String date2) {
		try {
			Date date1 = new Date();
			DateFormat df = DateFormat.getDateTimeInstance();
			System.out.println(date1.after(df.parse(date2)));
			return date1.after(df.parse(date2));
		} catch (ParseException e) {
			System.out.print(e.getMessage());
			return false;
		}
	}

	private void noTable() {
		Toast.makeText(this, "没有输入正确的桌台号，请重新输入", Toast.LENGTH_SHORT).show();
	}

	/**
	 * 发送异步处理
	 */
	public class sendTask extends AsyncTask<Void, Void, Boolean> {

		// 执行onPreExecute()完后立即调用
		@Override
		protected Boolean doInBackground(Void... params) {
			// 点菜明细表
			String bhd = JsonUntil.BHDListToJson(SO.getBusHitDetailList());

			List<BusHitMaster> bhmlist = new ArrayList<BusHitMaster>();
			bhmlist.add(busHitMaster);
			SO.setBusHitMasterList(bhmlist);
			// 点菜主表
			String bhm = JsonUntil.BHMListToJson(SO.getBusHitMasterList());
			// 套餐
			String bhs = JsonUntil.BusSerieshitListToJson(SO
					.getBusSerieshitList());
			Log.d("bhd", bhd);
			Log.d("bhm", bhm);
			Log.d("bhs", bhs);

			String temps = PostWebServiceData.PostHitMaster(tempwsdl, bhm, bhd,
					bhs);
			Log.d("temps", temps);
			if (temps != "" || temps.length() > 1) {
				return false;
			}

			return true;
		}

		// doInBackground后执行
		// result 的得自于doInBackgroun
		@Override
		protected void onPostExecute(Boolean result) {

			if (!result) {
				Common.alertalam(SurePost.this, "发送失败", "发送失败，请重新发送！");
			} else {

				StringBuffer sb = new StringBuffer("");
				// 热菜叫单
				if (cb1.isChecked()) {
					CalledSingle(0);
					sb.append("热菜,");
				}
				// 冷菜叫单
				if (cb2.isChecked()) {
					CalledSingle(1);
					sb.append("冷菜");
				}
				if (cb1.isChecked() || cb2.isChecked()) {
					if (sb.substring(sb.length() - 1, sb.length()).equals(",")) {
						sb.substring(0, sb.length() - 1);

					}
					sb.append("已叫单.");
				}

				// 热菜发送
				if (cb3.isChecked()) {
					send(0);
					sb.append("热菜,");
				}
				// 冷菜发送
				if (cb4.isChecked()) {
					send(1);
					sb.append("冷菜,");
				}
				// 酒水发送
				if (cb5.isChecked()) {
					send(2);
					sb.append("酒水");
				}

				if (cb3.isChecked() || cb4.isChecked() || cb5.isChecked()) {
					if (sb.substring(sb.length() - 1, sb.length()).equals(",")) {
						sb.substring(0, sb.length() - 1);

					}

					sb.append("已发送");
				}

				Common.alertFinishLong(SurePost.this, sb.toString());
				SO.getBusHitMasterList().clear();
				SO.getBusHitDetailList().clear();
				SO.getBusSerieshitList().clear();
			}
		}

	}

}
